package com.itheima.reggie.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.EmployeeHolder;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 页面访问拦截器
 */
@Component
public class ReggieInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取session对象,判断登录状态,如果一登录,则放行
        Employee employee = (Employee) request.getSession().getAttribute(Constant.SESSION_EMPLOYEE);
        if (employee !=null){
            EmployeeHolder.set(employee);//将员工对象放入线程工具类中
            //放行
            return true;
        }
        //如果未登录,
        String json = JSON.toJSONString(ResultInfo.error("NOTNOGIN"));
        response.getWriter().write(json);
        //不放行
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        EmployeeHolder.remove();//释放线程
    }
}
